import {Modal, Form, Input, Upload, Button, Select, message} from 'antd'
import React, {useEffect, useState} from "react";
import { apiInterceptors, getRole, distributeRoleForUser } from '@/client/api';
const DistributeRole = ({ setModal, userId, successCall, roleList }:any) => {
  const [options, setOptions] = useState([])
  const [roleIds, setRoleIds] = useState([])

  const getRoleList = async () => {
    const param = {
      page_num: 1,
      page_size: 9999
    }
    const [_, roleList] = await apiInterceptors(getRole(param))
    const optionList = roleList.data.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setOptions(optionList)
  }
  const filterOption = (input: string, option: { label: string; value: string }) => option?.label.includes(input)
  const submitHandle = async () => {
    if (!roleIds.length) return message.warning('请选择角色')
    const param = {
      role_list: roleIds,
      user_id: userId
    }
    const [_, data] = await apiInterceptors(distributeRoleForUser(param))
    if (data?.error_list.length) {
      let labelArr: string[] = []
      data.error_list.forEach((errId:number) => {
        const item:any = options.find((item:any) => item.value === String(errId))
        if (item) {
          labelArr.push(item.label)
        }
      })
      message.error(`分配角色${labelArr.toString()}失败`)
    } else {
      message.success('操作成功')
    }
    setModal(false)
    successCall()
  }
  const cancelHandle = () => {
    setModal(false)
  }

  const handleChange = (value: []) => {
    setRoleIds(value)
  }

  useEffect(() => {
    getRoleList()
    if (roleList.length) {
      setRoleIds(roleList.map((item:any)=> item.id))
    }
  },[])
  return (<>
    <Modal
      title='分配角色'
      open={true}
      onOk={submitHandle} onCancel={cancelHandle}
      width={500}
    >
      <Select
        mode="multiple"
        allowClear
        filterOption={filterOption}
        style={{ width: '100%', marginTop: '20px', marginBottom: '20px' }}
        placeholder="请选择角色"
        value={roleIds}
        onChange={handleChange}
        options={options}
      />
    </Modal>
  </>)
}

export default DistributeRole
